<?php
/**
 * DBERP 进销存系统
 *
 * ==========================================================================
 * @link      http://www.dberp.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   http://www.dberp.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Customer\Controller;

use Admin\Entity\Region;
use Customer\Entity\Customer;
use Customer\Entity\CustomerCategory;
use Customer\Form\CustomerForm;
use Customer\Form\ImportCustomerForm;
use Customer\Form\SearchCustomerForm;
use Customer\Service\CustomerManager;
use Doctrine\ORM\EntityManager;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use Sales\Entity\SalesOrder;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;

class CustomerController extends AbstractActionController
{
    private $translator;
    private $entityManager;
    private $customerManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager,
        CustomerManager $customerManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->customerManager  = $customerManager;
    }

    /**
     * 客户列表
     * @return array
     */
    public function indexAction()
    {
        $array = [];

        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchCustomerForm();
        $searchForm->get('customer_category_id')->setValueOptions($this->customerCommon()->customerCategoryOptions());
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }
        $array['searchForm'] = $searchForm;

        $query = $this->entityManager->getRepository(Customer::class)->findAllCustomer($search);
        $array['customerList'] = $this->adminCommon()->erpPaginator($query, $page);

        return $array;
    }

    /**
     * 添加客户
     * @return array|\Laminas\Http\Response
     */
    public function addAction()
    {
        $form = new CustomerForm($this->entityManager);

        $form->get('customerCategoryId')->setValueOptions($this->customerCommon()->customerCategoryOptions());

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                $this->customerManager->addCustomer($data, $this->adminSession('admin_id'));

                $message = sprintf($this->translator->translate('客户 %s 添加成功！'), $data['customerName']);
                $this->adminCommon()->addOperLog($message, $this->translator->translate('客户'));

                return $this->redirect()->toRoute('customer');
            }
        }

        if (empty($data)) $form->setData(['customerCode' => $this->codeAndNumber()->createCustomerCode()]);

        return ['form' => $form, 'region' => $this->adminCommon()->getRegionSub()];
    }

    /**
     * 编辑客户
     * @return array|\Laminas\Http\Response
     */
    public function editAction()
    {
        $customerId = (int) $this->params()->fromRoute('id', -1);

        $customerInfo = $this->entityManager->getRepository(Customer::class)->findOneByCustomerId($customerId);
        if($customerInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户不存在！'));
            return $this->redirect()->toRoute('customer');
        }

        $form = new CustomerForm($this->entityManager, $customerInfo);
        $form->get('customerCategoryId')->setValueOptions($this->customerCommon()->customerCategoryOptions());

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                $this->customerManager->editCustomer($data, $customerInfo);

                $message = sprintf($this->translator->translate('客户 %s 编辑成功！'), $data['customerName']);
                $this->adminCommon()->addOperLog($message, $this->translator->translate('客户'));

                return $this->redirect()->toRoute('customer');
            }
        } else $form->setData($customerInfo->valuesArray());

        return ['customer' => $customerInfo, 'form' => $form, 'region' => $this->adminCommon()->getRegionSub()];
    }

    /**
     * 批量修改
     * @return \Laminas\Http\Response
     */
    public function updateAllAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            if(!empty($data['select_id']) and !empty($data['editAllState'])) {
                $this->customerManager->editAllCustomer($data);

                $message = $this->translator->translate('批量处理成功！');
                $this->adminCommon()->addOperLog($message, $this->translator->translate('客户'));
            }
        }
        return $this->redirect()->toRoute('customer');
    }

    /**
     * 删除客户
     * @return \Laminas\Http\Response
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $customerId = (int) $this->params()->fromRoute('id', -1);

        $customerInfo = $this->entityManager->getRepository(Customer::class)->findOneByCustomerId($customerId);
        if($customerInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户不存在！'));
            return $this->redirect()->toRoute('customer');
        }

        $salesOrder = $this->entityManager->getRepository(SalesOrder::class)->findOneBy(['customerId' => $customerId]);
        if($salesOrder) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户有销售订单存在，不能删除！'));
            return $this->redirect()->toRoute('customer');
        }

        $this->customerManager->deleteCustomer($customerInfo);

        $this->getEventManager()->trigger('customer.delete.post', $this, ['customerId' => $customerId]);

        $message = sprintf($this->translator->translate('客户 %s 删除成功！'), $customerInfo->getCustomerName());
        $this->adminCommon()->addOperLog($message, $this->translator->translate('客户'));

        return $this->adminCommon()->toReferer();
    }

    /**
     * 客户批量导入
     * @return ImportCustomerForm[]|\Laminas\Http\Response
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function importCustomerAction()
    {
        @set_time_limit(600);

        $form = new ImportCustomerForm();

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                $customerCategoryList = $this->entityManager->getRepository(CustomerCategory::class)->findBy([]);
                if (empty($customerCategoryList)) {
                    $this->flashMessenger()->addWarningMessage($this->translator->translate('系统中没有客户分类，请添加后再导入 !'));
                    return $this->redirect()->toRoute('customer', ['action' => 'importCustomer']);
                }

                $customerCategoryArray = [];
                foreach ($customerCategoryList as $categoryValue) {
                    $customerCategoryArray[$categoryValue->getCustomerCategoryId()] = $categoryValue->getCustomerCategoryName();
                }

                $readerXlsx     = new Xlsx();
                $spreadsheet    = $readerXlsx->load($data['importFile']['tmp_name']);
                $sheetData      = $spreadsheet->getActiveSheet()->toArray(null, false, false, true);
                $rowCount       = count($sheetData);
                if ($rowCount == 1) {
                    $this->flashMessenger()->addWarningMessage($this->translator->translate('无导入信息!'));
                    return $this->redirect()->toRoute('customer', ['action' => 'importCustomer']);
                }

                $adminId        = $this->adminSession('admin_id');
                $regionStrArray = [];
                $nextCustomerId = $this->entityManager->getRepository(Customer::class)->getMaxCustomerId();
                $insertCustomerSql = '';
                $insertCustomerSqlArray = [];
                for ($i = 2; $i <= $rowCount; $i++) {
                    $customerCategoryId = (int) $sheetData[$i]['A'];
                    $customerName = addslashes($sheetData[$i]['B']);
                    $customerCode = $sheetData[$i]['C'];
                    $regionId = (int) $sheetData[$i]['D'];
                    if (!isset($customerCategoryArray[$customerCategoryId]) || empty($customerName) || empty($customerCode) || $regionId <= 0) {
                        continue;
                    }

                    $customerAddress = addslashes($sheetData[$i]['E']);
                    $customerContacts = addslashes($sheetData[$i]['F']);
                    $customerPhone = $sheetData[$i]['G'];
                    $customerTelephone = $sheetData[$i]['H'];
                    $customerEmail = $sheetData[$i]['I'];
                    $customerBank = addslashes($sheetData[$i]['J']);
                    $customerBankAccount = $sheetData[$i]['K'];
                    $customerTax = $sheetData[$i]['L'];
                    $customerInfo = addslashes($sheetData[$i]['M']);

                    $regionStr  = '';
                    if (isset($regionStrArray[$regionId])) $regionStr = $regionStrArray[$regionId];
                    else {
                        $regionInfo = $this->entityManager->getRepository(Region::class)->findOneBy(['regionId' => $regionId]);
                        if (!empty($regionInfo)) {
                            $regionStr = $this->entityManager->getRepository(Region::class)->getRegionStr($regionInfo->getRegionPath());
                            $regionStrArray[$regionId] = $regionStr;
                        }
                    }

                    $insertCustomerSql .= "($nextCustomerId, $customerCategoryId, '$customerName', '$customerCode', $regionId, '$regionStr', '$customerAddress', '$customerContacts', '$customerPhone', '$customerTelephone', '$customerEmail', '$customerBank', '$customerBankAccount', '$customerTax', '$customerInfo', $adminId),";
                    if ($i%3000 == 0) {
                        $insertCustomerSqlArray[] = rtrim($insertCustomerSql, ',');
                        $insertCustomerSql = '';
                    }

                    $nextCustomerId++;
                }

                if (!empty($insertCustomerSql)) {
                    $this->entityManager->beginTransaction();
                    try {
                        $this->entityManager->getConnection()->executeStatement('INSERT INTO dberp_customer (customer_id, customer_category_id, customer_name, customer_code, region_id, region_values, customer_address, customer_contacts, customer_phone, customer_telephone, customer_email, customer_bank, customer_bank_account, customer_tax, customer_info, admin_id) VALUES '.rtrim($insertCustomerSql, ','));
                        if (!empty($insertCustomerSqlArray)) foreach ($insertCustomerSqlArray as $insertCustomerSqlValue) {
                            $this->entityManager->getConnection()->executeStatement('INSERT INTO dberp_customer (customer_id, customer_category_id, customer_name, customer_code, region_id, region_values, customer_address, customer_contacts, customer_phone, customer_telephone, customer_email, customer_bank, customer_bank_account, customer_tax, customer_info, admin_id) VALUES '.$insertCustomerSqlValue);
                        }
                        $this->entityManager->commit();
                        $this->adminCommon()->addOperLog($this->translator->translate('客户批量导入成功!'), $this->translator->translate('客户'));
                    } catch (\Exception $e) {
                        $this->entityManager->rollback();
                        $this->flashMessenger()->addErrorMessage($this->translator->translate('导入失败，请检查数据格式是否正确！'));
                        return $this->redirect()->toRoute('customer', ['action' => 'importCustomer']);
                    }
                }
                return $this->redirect()->toRoute('customer');
            }
        }

        return [
            'form' => $form
        ];
    }

    /**
     * 通过客户id检索客户
     * @return JsonModel
     */
    public function customerIdSearchAction()
    {
        $array = ['state' => 'false'];

        $customerId = (int) $this->params()->fromPost('customerId', 0);
        $customerInfo = $this->entityManager->getRepository(Customer::class)->findOneByCustomerId($customerId);
        if($customerInfo) {
            $array['state'] = 'ok';
            $array['result']= $customerInfo->valuesArray();
        }

        return new JsonModel($array);
    }
}